package com.zshy.base.kit.lang;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * pinyin工具类
 *
 * @author zhouhengzhe
 * @公众号 小白的Java进阶之路
 */
@Slf4j
@UtilityClass
public class PinyinKit {
    private final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

    static {
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    /**
     * 将汉字转换成拼音
     *
     * @param hanyu 要转换的汉字字符串
     * @return 转换后的拼音字符串，如果转换失败则返回原汉字字符串
     */
    public String toPinyin(String hanyu) {
        try {
            return PinyinHelper.toHanYuPinyinString(hanyu, format, "", Boolean.FALSE);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("转换拼音失败", e);
            return hanyu;
        }
    }

    /**
     * 将汉字转换成拼音，并转为大写
     *
     * @param hanyu 要转换的汉字字符串
     * @return 转换后的拼音大写字符串，如果转换失败则返回原汉字字符串
     */
    public String toPinyinUppercase(String hanyu) {
        try {
            return PinyinHelper.toHanYuPinyinString(hanyu, format, "", Boolean.FALSE).toUpperCase();
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("转换拼音失败", e);
            return hanyu;
        }
    }
}
